package com.obas.view.explorer
{
   import com.ease.core.events.ViewOperationEvent;
   import com.ease.framework.CommandCompletionEvent;
   import com.obas.business.feature.CreateBusinessFunctionDialog;
   import com.obas.business.view.scenario.CreateBusinessSenarioDialog;
   import com.obas.business.view.usecase.CreateBusinessUseCaseDialog;
   import com.obas.component.tree.treeclass.Node;
   import com.obas.constants.TestingLibConstants;
   import com.obas.event.DataRefreshEvent;
   import com.obas.event.ItestOperationEvent;
   import com.obas.flex.common.util.ListDataUtil;
   import com.obas.model.business.BusinessFunction;
   import com.obas.model.business.BusinessRepository;
   import com.obas.model.business.BusinessScenario;
   import com.obas.model.business.BusinessUsecase;
   import com.obas.view.menu.BusinessCaseMenu;
   import com.obas.view.menu.BusinessFunctionMenu;
   import com.obas.view.menu.BusinessScenarioMenu;
   import com.obas.view.menu.RepositoryMenu;
   import com.ease.component.managers.ConfirmHelper;

   import flash.events.EventDispatcher;

   import mx.collections.ArrayCollection;
   import mx.controls.Alert;
   import mx.events.CloseEvent;
   import mx.events.ListEvent;
   import mx.managers.PopUpManager;

   [Event(name="{com.ease.core.events.ViewOperationEvent.REQUEST_ID}", type="com.ease.core.events.ViewOperationEvent")]
   [Event(name="{com.obas.event.ItestOperationEvent.REQUEST_ID}", type="com.obas.event.ItestOperationEvent")]
   public class ITestBusinessExplorerViewMediator extends EventDispatcher {

      private var listUtil:ListDataUtil = new ListDataUtil(keyFunction);

      public var _view:ITestBusinessExplorerView;

      [InjectableView]
      public function get view():ITestBusinessExplorerView {
         return _view;
      }

      public function set view(value:ITestBusinessExplorerView):void {
         _view = value;
         init();
      }

      private function init():void {
         //获取所有的业务场景库
         dispatchEvent(new ItestOperationEvent([],ItestOperationEvent.GET_BUSINESSREPOSITORY));
         //菜单事件
         //业务场景库
         view.addEventListener(RepositoryMenu.CREATE_BUSINESS_SCENARIO, onCreateBusinessScenario);
         view.addEventListener(RepositoryMenu.DELETE_REPOSITORY, onDeleteRepository);

         //业务场景
         view.addEventListener(BusinessScenarioMenu.CREATE_BUSINESS_CASE, onCreateBusinessCase);
         view.addEventListener(BusinessScenarioMenu.DELETE_BUSINESS_SCENARIO, onDeleteBusinessScenario);

         //业务用例
         view.addEventListener(BusinessCaseMenu.CREATE_BUSINESS_FUNCTION, onCreateBusinessFunction);
         view.addEventListener(BusinessCaseMenu.DELETE_BUSINESS_CASE, onDeleteBusinessCase);

         //业务功能
         view.addEventListener(BusinessFunctionMenu.DELETE_BUSINESS_FUNCTION, onDeleteBusinessFunction);

         view.navBusinessTree.addEventListener(ListEvent.ITEM_DOUBLE_CLICK, onDoubleClick);
      }

      private function onDoubleClick(e:*):void {
         var selectedNode:Node = view.navBusinessTree.selectedItem as Node;
         var paramOther:Object = new Object();
         paramOther.targetView = "commonView";
         paramOther.className = "com.obas.view.EntityView";
         paramOther.createNew = "true";
         paramOther.autoOpen = "true";
         paramOther.model = selectedNode.entity;
         dispatchEvent(new ViewOperationEvent([paramOther.targetView], paramOther));
      }

      private function onDeleteBusinessFunction(e:*):void {
         ConfirmHelper.showConfirmDialog("删除", "确定要删除该业务功能[" + view.navBusinessTree.selectedItem.name + "]？", onDeleteBusinessFunctionClose);
      }

      private function onDeleteBusinessFunctionClose(evt:CloseEvent):void {
         if (evt.detail == Alert.YES) {
            dispatchEvent(new ItestOperationEvent([view.navBusinessTree.selectedItem.entity, view.navBusinessTree.selectedItem], ItestOperationEvent.DELETE_BUSINESSFUNCTION));
         }
      }

      private function onDeleteBusinessCase(e:*):void {
         ConfirmHelper.showConfirmDialog("删除", "确定要删除该业务用例[" + view.navBusinessTree.selectedItem.name + "]？", onDeleteBusinessCaseClose);
      }

      private function onDeleteBusinessCaseClose(evt:CloseEvent):void {
         if (evt.detail == Alert.YES) {
            dispatchEvent(new ItestOperationEvent([view.navBusinessTree.selectedItem.entity, view.navBusinessTree.selectedItem], ItestOperationEvent.DELETE_BUSINESSUSECASE));
         }
      }

      private function onCreateBusinessFunction(e:*):void {
         var dialog:CreateBusinessFunctionDialog = PopUpManager.createPopUp(view.root, CreateBusinessFunctionDialog, true) as CreateBusinessFunctionDialog;
         dialog.parentProject = view.navBusinessTree.selectedItem as Node;
         PopUpManager.centerPopUp(dialog);
      }

      private function onDeleteBusinessScenario(e:*):void {
         ConfirmHelper.showConfirmDialog("删除", "确定要删除该业务场景[" + view.navBusinessTree.selectedItem.name + "]？", onDeleteBusinessScenarioClose);
      }

      private function onDeleteBusinessScenarioClose(evt:CloseEvent):void {
         if (evt.detail == Alert.YES) {
            dispatchEvent(new ItestOperationEvent([view.navBusinessTree.selectedItem.entity, view.navBusinessTree.selectedItem], ItestOperationEvent.DELETE_BUSINESSSCENARIO));
         }
      }

      private function onCreateBusinessCase(e:*):void {
         var dialog:CreateBusinessUseCaseDialog = PopUpManager.createPopUp(view.root, CreateBusinessUseCaseDialog, true) as CreateBusinessUseCaseDialog;
         dialog.parentProject = view.navBusinessTree.selectedItem as Node;
         PopUpManager.centerPopUp(dialog);
      }

      private function onDeleteRepository(e:*):void {
         ConfirmHelper.showConfirmDialog("删除", "确定要删除该业务场景库[" + view.navBusinessTree.selectedItem.name + "]？", onDeleteRepositoryClose);
      }

      private function onDeleteRepositoryClose(evt:CloseEvent):void {
         if (evt.detail == Alert.YES) {
            dispatchEvent(new ItestOperationEvent([view.navBusinessTree.selectedItem.entity, view.navBusinessTree.selectedItem], ItestOperationEvent.DELETE_BUSINESSREPOSITORY));
         }
      }

      private function onCreateBusinessScenario(e:*):void {
         var dialog:CreateBusinessSenarioDialog = PopUpManager.createPopUp(view.root, CreateBusinessSenarioDialog, true) as CreateBusinessSenarioDialog;
         dialog.parentProject = view.navBusinessTree.selectedItem as Node;
         PopUpManager.centerPopUp(dialog);
      }

      [ResponseHandler("{com.obas.event.ItestOperationEvent.RETURN_ID}")]
      public function onItestOperationEvent(event:CommandCompletionEvent):void {
         if (event.error) {
            return ;
         }

         var request:ItestOperationEvent = event.request as ItestOperationEvent;
         if (request.actionType == ItestOperationEvent.GET_BUSINESSREPOSITORY) {
            var results:ArrayCollection = event.result as ArrayCollection;
            for each (var br:BusinessRepository in results) {
               var childNode:Node = view.navBusinessTree.nodeFactory.createNode(br);
               childNode.type = TestingLibConstants.ITEMTYPE_BUSINESSREPOSITORY;
               view.treeNodes.addItem(childNode);
            }
         }
         else if (request.actionType == ItestOperationEvent.DELETE_BUSINESSREPOSITORY ||
            request.actionType == ItestOperationEvent.DELETE_BUSINESSSCENARIO ||
            request.actionType == ItestOperationEvent.DELETE_BUSINESSUSECASE ||
            request.actionType == ItestOperationEvent.DELETE_BUSINESSFUNCTION ) {
            var node:Node = request.spec[1];
            var parentNode:Node = node.parentNode;
            if (parentNode) {
               parentNode.children.removeItemAt(parentNode.children.getItemIndex(node));
               parentNode.children.refresh();
            }
            else {
               view.treeNodes.removeItemAt(view.treeNodes.getItemIndex(node));
            }
            view.navBusinessTree.invalidateDisplayList();
         }
      }


      [EventHandler("{com.obas.event.DataRefreshEvent.REQUEST_ID}")]
      public function onDataRefreshEvent(event:DataRefreshEvent):void {
         switch (event.actionType) {
            case DataRefreshEvent.TYPE_DELETE :
               deleteItems(event.spec.data);
               break;
            case DataRefreshEvent.TYPE_ADD_UPDATE :
               var parentNode:Node = event.spec.context;
               var datas:ArrayCollection = event.spec.data;
               if (datas && datas.length > 0) {
                  var item:* = datas.getItemAt(0);
                  var nodeType:String = getNodeType(item);
                  if(nodeType == "") {
                     return;
                  }
                  var childNode:Node = view.navBusinessTree.nodeFactory.createNode(item);
                  childNode.type = nodeType;
                  if (nodeType == TestingLibConstants.ITEMTYPE_BUSINESSFUNCTION) {
                     childNode.children = null;
                  }
                  var nodes:Array = [childNode];
                  if (parentNode) {
                     childNode.parentNode = parentNode;
                     listUtil.addOrUpdateItems(parentNode.children.source, nodes, true);
                     parentNode.children.refresh();
                  }
                  else {
                     listUtil.addOrUpdateItems(view.treeNodes.source, nodes, true);
                     view.treeNodes.refresh();
                  }
                  view.navBusinessTree.invalidateDisplayList();
               }

               break;
         }
      }

      private function keyFunction(item:*):String {
         return item.entity.id + "";
      }

      private function deleteItems(items:ArrayCollection):void {
      }

      public function getNodeType(item:*):String {
         if (item is BusinessRepository) {
            return TestingLibConstants.ITEMTYPE_BUSINESSREPOSITORY;
         }
         else if (item is BusinessScenario) {
            return TestingLibConstants.ITEMTYPE_BUSINESSSCENARIO;
         }
         else if (item is BusinessUsecase) {
            return TestingLibConstants.ITEMTYPE_BUSINESSUSECASE;
         }
         else if (item is BusinessFunction) {
            return TestingLibConstants.ITEMTYPE_BUSINESSFUNCTION;
         }
         return "";
      }

   }
}